package com.all.utils;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectionUtils {
	/*
	 * 得到某个类的属性
	 * */
	@SuppressWarnings("rawtypes")
	public static Object getProperty(Object owner, String fieldName) throws Exception {  
		
	     Class ownerClass = owner.getClass();   

	     Field field = ownerClass.getField(fieldName);   

	     Object property = field.get(owner);   

	     return property;   

	}  
	/*
	 * 得到某个类的静态属性
	 * */
	@SuppressWarnings("rawtypes")
	public static Object getStaticProperty(String className, String fieldName)   
            throws Exception {   
		  	Class ownerClass = Class.forName(className);   

		     Field field = ownerClass.getField(fieldName);   

		     Object property = field.get(ownerClass);   

		     return property;   
	}
	/*
	 * 执行某对象的方法
	 * */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Object invokeMethod(Object owner, String methodName, Object[] args) throws Exception {   
	     Class ownerClass = owner.getClass();   

	     Class[] argsClass = new Class[args.length];   
	     
	     if(args!=null)
	     for (int i = 0, j = args.length; i < j; i++) {   

	         argsClass[i] = args[i].getClass();   

	     }   

	      Method method = ownerClass.getMethod(methodName,argsClass);   

	     return method.invoke(owner, args);   

	}  
	
	/*
	 * 执行某对象的方法
	 * */

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Object invokeStaticMethod(String className, String methodName,   
	             Object[] args) throws Exception {   

	     Class ownerClass = Class.forName(className);   

	     Class[] argsClass = new Class[args.length];   

	     for (int i = 0, j = args.length; i < j; i++) {   

	         argsClass[i] = args[i].getClass();   

	     }   

	    Method method = ownerClass.getMethod(methodName,argsClass);   

	     return method.invoke(null, args);   

	 }  
	
	/*
	 * 执行某对象的方法
	 * */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Object newInstance(String className, Object[] args) throws Exception {   
	     Class newoneClass = Class.forName(className);   

	     Class[] argsClass = new Class[args.length];   

	     if(args!=null)
	     for (int i = 0, j = args.length; i < j; i++) {   

	         argsClass[i] = args[i].getClass();   

	     }   

	     Constructor cons = newoneClass.getConstructor(argsClass);   

	     return cons.newInstance(args);   

	}  
	
	/*
	 *判断是否为某个类的实例
	 * */
	@SuppressWarnings("rawtypes")
	public boolean isInstance(Object obj, Class cls) {   
	     return cls.isInstance(obj);   

	}  
}
